﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuanLyNganHangDe.BLL;
using QuanLyNganHangDe.DAL.Models;

namespace QuanLyNganHangDe.GUI.TacNghiep
{
    public partial class FormHocPhan_Import : Form
    {
        /// <summary>
        /// Thông tin về học phần sẽ ra đề thi
        /// </summary>
        class HocPhanImport
        {
            public int SoThuTu { get; set; }
            public string MaHocPhan { get; set; }
            public string TenHocPhan { get; set; }
            public int SoTinChi { get; set; }
            public string TenKhoa { get; set; }
            public bool DuocSuDungTaiLieu { get; set; }
            public int ThoiGianLamBai { get; set; }
            public string TrangThai { get; set; }
            public void SetInvalid(string trangThai)
            {
                IsValid = false;
                TrangThai = trangThai;
                SoTinChi = 0;
            }
            public bool IsValid { get; set; }
        }

        private QuanLyNganHangDe.DAL.Models.QLNHD_KHContext m_DbContext = null;
        private QuanLyNganHangDe.DAL.Models.QLNHD_KHContext DbContext
        {
            get
            {
                if (m_DbContext == null)
                    m_DbContext = QLNHD_KHContext.GetContext();
                return m_DbContext;
            }
        }

        private void ReleaseDbContext()
        {
            if (m_DbContext != null)
            {
                m_DbContext.Dispose();
            }
        }

        public FormHocPhan_Import()
        {
            InitializeComponent();
        }

        private void lnkSelectFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var dlg = new OpenFileDialog();
            dlg.Title = "Chọn tệp Excel để nạp thông tin đợt thi...";
            dlg.Filter = "Tệp Excel (*.XLS, *XLSX)|*.xls;*.xlsx";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtExcelFileName.Text = dlg.FileName;
                NapDanhSachBangTinh();
            }
        }

        private void lnkGetSheetList_Click(object sender, EventArgs e)
        {
            NapDanhSachBangTinh();
        }

        private void NapDanhSachBangTinh()
        {
            ep.Clear();
            var filename = txtExcelFileName.Text;
            if (string.IsNullOrEmpty(filename))
            {
                //DialogUtils.ShowError("Bạn phải chọn tệp Excel chứa danh sách các học phần ra đề thi");
                //return;
                ep.SetIconAlignment(lblExcelFilename, ErrorIconAlignment.MiddleLeft);
                ep.SetError(lblExcelFilename, "Bạn chưa chọn tệp Excel");
                return;
            }
            try
            {
                var ei = new BLL.Excel.ExcelImporter(filename);
                var lstSheet = ei.GetSheetNameList();

                cbxSheet.Items.Clear();
                foreach (var sheet in lstSheet)
                    cbxSheet.Items.Add(sheet);

                if (lstSheet.Count > 0)
                {
                    cbxSheet.SelectedIndex = 0;
                    for (int idx = 0; idx < lstSheet.Count; idx++)
                    {
                        if (lstSheet[idx].FriendlyName.ToUpper() == "SHEET1")
                        {
                            cbxSheet.SelectedIndex = idx;
                            break;
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                ep.SetIconAlignment(lblExcelFilename, ErrorIconAlignment.MiddleLeft);
                ep.SetError(lblExcelFilename, "Không thể nạp danh sách bảng tính\r\n" + exc.Message);
            }
        }

        private void btnReadSheetData_Click(object sender, EventArgs e)
        {
            #region var ei = new ExcelImporter() or return;
            ep.Clear();
            var filename = txtExcelFileName.Text;
            if (string.IsNullOrEmpty(filename))
            {
                //DialogUtils.ShowError("Bạn phải chọn tệp Excel chứa danh sách các học phần ra đề thi");
                ep.SetIconAlignment(lblExcelFilename, ErrorIconAlignment.MiddleLeft);
                ep.SetError(lblExcelFilename, "Bạn chưa chọn tệp Excel");
                return;
            }
            var ei = new BLL.Excel.ExcelImporter(filename);
            string sheetName = null;
            BLL.Excel.SheetName oSheetName = null;
            if (cbxSheet.SelectedItem != null)
                oSheetName = cbxSheet.SelectedItem as BLL.Excel.SheetName;
            if (oSheetName != null)
                sheetName = oSheetName.Name;
            if (string.IsNullOrEmpty(sheetName))
            {
                //DialogUtils.ShowError("Bạn phải chọn bảng tính chứa danh danh sách các học phần ra đề thi");
                ep.SetIconAlignment(lblSheetname, ErrorIconAlignment.MiddleLeft);
                ep.SetError(lblSheetname, "Bạn chưa chọn bảng tính");
                return;
            }
            #endregion

            var bw = new BackgroundWorker() { WorkerSupportsCancellation = true, WorkerReportsProgress = true };
            var lstHocPhanImport = new List<HocPhanImport>();
            bw.DoWork += (oSender, oE) =>
            {
                var dt = ei.ReadData(sheetName, txtDiaChi.Text, txtDiaChiDen.Text, false);

                foreach (DataRow drow in dt.Rows)
                {
                    // Cột đầu tiên là STT
                    var stSTT = Convert.ToString(drow[0]);
                    if (string.IsNullOrEmpty(stSTT))
                        break;
                    var stt = Convert.ToInt32(stSTT);
                    var maHP = Convert.ToString(drow[1]).Trim();
                    var tenHP = Convert.ToString(drow[2]).Trim();
                    var tenKhoa = Convert.ToString(drow[3]).Trim();
                    var dcSDTL = Convert.ToString(drow[4]);
                    bool dcSuDungTL = false;
                    if (dcSDTL != null)
                        dcSDTL = dcSDTL.Trim();
                    if (string.IsNullOrEmpty(dcSDTL))
                        dcSuDungTL = false;
                    else
                        dcSuDungTL = true;
                    var soTC = int.Parse(maHP[maHP.Length - 1].ToString());
                    var thoiGianLB = 90;
                    if (soTC <= 2)
                        thoiGianLB = 90;
                    else
                        thoiGianLB = 120;
                    var hocPhanImport = new HocPhanImport()
                    {
                        MaHocPhan = maHP,
                        SoThuTu = stt,
                        SoTinChi = soTC,
                        TenHocPhan = tenHP,
                        TenKhoa = tenKhoa,
                        ThoiGianLamBai = thoiGianLB,
                        DuocSuDungTaiLieu = dcSuDungTL
                    };

                    var hocphan = BizHocPhan.GetHocPhan(maHP);
                    if (hocphan == null)
                    {
                        hocPhanImport.IsValid = true;
                    }
                    else
                    {
                        hocPhanImport.SetInvalid("Đã tồn tại học phần này");
                    }
                    lstHocPhanImport.Add(hocPhanImport);
                }


            };
            bw.RunWorkerCompleted += (oSender, oE) =>
            {
                #region RunWorkerCompleted
                UpdateGuiAsFree();
                bsHocPhanThi.DataSource = new SortableBindingList<HocPhanImport>(lstHocPhanImport);
                gridHocPhanImport.AutoGenerateColumns = false;
                gridHocPhanImport.DataSource = bsHocPhanThi;
                #endregion
            };
            bw.ProgressChanged += (oSender, oE) =>
            {
                #region ProgressChanged
                gridHocPhanImport.Refresh();
                DialogUtils.ShowMessage("Đã lưu dữ liệu thành công");
                #endregion
            };
            UpdateGuiAsBusy(bw);
            bw.RunWorkerAsync();


        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnCreateDeInRa_Click(object sender, EventArgs eventArgs)
        {

        }

        private void UpdateGuiAsBusy(BackgroundWorker bw)
        {
            //btnCreateDeInRa.Text = "Huỷ ngang";
            //btnCreateDeInRa.Tag = bw;
            btnSave.Enabled = false;
            btnClose.Enabled = false;
            picBusy.Visible = true;
        }

        private void UpdateGuiAsFree()
        {
            //btnCreateDeInRa.Text = "Tạo đề thi";
            //btnCreateDeInRa.Tag = null;
            btnSave.Enabled = true;
            btnClose.Enabled = true;
            picBusy.Visible = false;
        }

        private DataGridViewCellStyle m_StrikeoutStyle = null;
        private DataGridViewCellStyle StrikeoutStyle
        {
            get
            {
                if (m_StrikeoutStyle == null)
                {
                    m_StrikeoutStyle = new DataGridViewCellStyle(gridHocPhanImport.DefaultCellStyle);
                    m_StrikeoutStyle.Font = new Font(m_StrikeoutStyle.Font, FontStyle.Strikeout);
                    m_StrikeoutStyle.ForeColor = Color.Gray;
                }
                return m_StrikeoutStyle;
            }
        }

        private void gridHocPhanThi_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            for (int i = 0; i < gridHocPhanImport.Rows.Count; i++)
            {
                DataGridViewRow dgrow = gridHocPhanImport.Rows[i];
                var hocPhanThi = dgrow.DataBoundItem as HocPhanImport;
                if (hocPhanThi.IsValid)
                {
                    for (int j = 1; j <= 6; j++)
                        dgrow.Cells[j].Style = null;
                }
                else
                {
                    for (int j = 1; j <= 6; j++)
                        dgrow.Cells[j].Style = StrikeoutStyle;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            gridHocPhanImport.ExportFilePath = "TaoDeThi-LOG.xls";
            gridHocPhanImport.ToExcel(exportVisibleColumnsOnly: true);
        }

        private void btnSaveDeInRa_Click(object sender, EventArgs ea)
        {

        }

        private void FormDotThi_Import_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.ReleaseDbContext();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            var bw = new BackgroundWorker() { WorkerSupportsCancellation = true, WorkerReportsProgress = true };
            bw.DoWork += (oSender, oE) =>
            {
                #region DoWork
                var context = this.DbContext;
                var lstHocPhanImport = oE.Argument as SortableBindingList<HocPhanImport>;
                for (int k = 0; k < lstHocPhanImport.Count; k++)
                {
                    var hocPhanImport = lstHocPhanImport[k];

                    #region
                    try
                    {
                        if (hocPhanImport.IsValid)
                            BizHocPhan.AddHocPhan(hocPhanImport.MaHocPhan, hocPhanImport.TenHocPhan, hocPhanImport.SoTinChi, hocPhanImport.ThoiGianLamBai, hocPhanImport.DuocSuDungTaiLieu, hocPhanImport.TenKhoa.Trim());
                    }
                    catch (Exception exc)
                    {
                        hocPhanImport.TrangThai = "Lỗi: " + exc.Message;
                    }
                    #endregion
                }
                #endregion
            };
            bw.RunWorkerCompleted += (oSender, oE) =>
            {
                #region RunWorkerCompleted
                UpdateGuiAsFree();
                DialogUtils.ShowMessage("Đã lưu dữ liệu thành công");
                #endregion
            };
            bw.ProgressChanged += (oSender, oE) =>
            {
                #region ProgressChanged
                gridHocPhanImport.Refresh();
                #endregion
            };

            UpdateGuiAsBusy(bw);
            bw.RunWorkerAsync(bsHocPhanThi.DataSource);
        }
    }
}
